package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.sales.domain.Competitor;
import cn.ibizlab.businesscentral.core.sales.service.ICompetitorService;
import cn.ibizlab.businesscentral.core.sales.filter.CompetitorSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"竞争对手" })
@RestController("CentralApi-competitor")
@RequestMapping("")
public class CompetitorResource {

    @Autowired
    public ICompetitorService competitorService;

    @Autowired
    @Lazy
    public CompetitorMapping competitorMapping;

    @PreAuthorize("hasPermission(this.competitorMapping.toDomain(#competitordto),'iBizBusinessCentral-Competitor-Create')")
    @ApiOperation(value = "新建竞争对手", tags = {"竞争对手" },  notes = "新建竞争对手")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors")
    public ResponseEntity<CompetitorDTO> create(@RequestBody CompetitorDTO competitordto) {
        Competitor domain = competitorMapping.toDomain(competitordto);
		competitorService.create(domain);
        CompetitorDTO dto = competitorMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.competitorMapping.toDomain(#competitordtos),'iBizBusinessCentral-Competitor-Create')")
    @ApiOperation(value = "批量新建竞争对手", tags = {"竞争对手" },  notes = "批量新建竞争对手")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<CompetitorDTO> competitordtos) {
        competitorService.createBatch(competitorMapping.toDomain(competitordtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "competitor" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.competitorService.get(#competitor_id),'iBizBusinessCentral-Competitor-Update')")
    @ApiOperation(value = "更新竞争对手", tags = {"竞争对手" },  notes = "更新竞争对手")
	@RequestMapping(method = RequestMethod.PUT, value = "/competitors/{competitor_id}")
    public ResponseEntity<CompetitorDTO> update(@PathVariable("competitor_id") String competitor_id, @RequestBody CompetitorDTO competitordto) {
		Competitor domain  = competitorMapping.toDomain(competitordto);
        domain .setCompetitorid(competitor_id);
		competitorService.update(domain );
		CompetitorDTO dto = competitorMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.competitorService.getCompetitorByEntities(this.competitorMapping.toDomain(#competitordtos)),'iBizBusinessCentral-Competitor-Update')")
    @ApiOperation(value = "批量更新竞争对手", tags = {"竞争对手" },  notes = "批量更新竞争对手")
	@RequestMapping(method = RequestMethod.PUT, value = "/competitors/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<CompetitorDTO> competitordtos) {
        competitorService.updateBatch(competitorMapping.toDomain(competitordtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.competitorService.get(#competitor_id),'iBizBusinessCentral-Competitor-Remove')")
    @ApiOperation(value = "删除竞争对手", tags = {"竞争对手" },  notes = "删除竞争对手")
	@RequestMapping(method = RequestMethod.DELETE, value = "/competitors/{competitor_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("competitor_id") String competitor_id) {
         return ResponseEntity.status(HttpStatus.OK).body(competitorService.remove(competitor_id));
    }

    @PreAuthorize("hasPermission(this.competitorService.getCompetitorByIds(#ids),'iBizBusinessCentral-Competitor-Remove')")
    @ApiOperation(value = "批量删除竞争对手", tags = {"竞争对手" },  notes = "批量删除竞争对手")
	@RequestMapping(method = RequestMethod.DELETE, value = "/competitors/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        competitorService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.competitorMapping.toDomain(returnObject.body),'iBizBusinessCentral-Competitor-Get')")
    @ApiOperation(value = "获取竞争对手", tags = {"竞争对手" },  notes = "获取竞争对手")
	@RequestMapping(method = RequestMethod.GET, value = "/competitors/{competitor_id}")
    public ResponseEntity<CompetitorDTO> get(@PathVariable("competitor_id") String competitor_id) {
        Competitor domain = competitorService.get(competitor_id);
        CompetitorDTO dto = competitorMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取竞争对手草稿", tags = {"竞争对手" },  notes = "获取竞争对手草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/competitors/getdraft")
    public ResponseEntity<CompetitorDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(competitorMapping.toDto(competitorService.getDraft(new Competitor())));
    }

    @ApiOperation(value = "检查竞争对手", tags = {"竞争对手" },  notes = "检查竞争对手")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody CompetitorDTO competitordto) {
        return  ResponseEntity.status(HttpStatus.OK).body(competitorService.checkKey(competitorMapping.toDomain(competitordto)));
    }

    @PreAuthorize("hasPermission(this.competitorMapping.toDomain(#competitordto),'iBizBusinessCentral-Competitor-Save')")
    @ApiOperation(value = "保存竞争对手", tags = {"竞争对手" },  notes = "保存竞争对手")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/save")
    public ResponseEntity<Boolean> save(@RequestBody CompetitorDTO competitordto) {
        return ResponseEntity.status(HttpStatus.OK).body(competitorService.save(competitorMapping.toDomain(competitordto)));
    }

    @PreAuthorize("hasPermission(this.competitorMapping.toDomain(#competitordtos),'iBizBusinessCentral-Competitor-Save')")
    @ApiOperation(value = "批量保存竞争对手", tags = {"竞争对手" },  notes = "批量保存竞争对手")
	@RequestMapping(method = RequestMethod.POST, value = "/competitors/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<CompetitorDTO> competitordtos) {
        competitorService.saveBatch(competitorMapping.toDomain(competitordtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Competitor-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Competitor-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"竞争对手" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/competitors/fetchdefault")
	public ResponseEntity<List<CompetitorDTO>> fetchDefault(CompetitorSearchContext context) {
        Page<Competitor> domains = competitorService.searchDefault(context) ;
        List<CompetitorDTO> list = competitorMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Competitor-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Competitor-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"竞争对手" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/competitors/searchdefault")
	public ResponseEntity<Page<CompetitorDTO>> searchDefault(@RequestBody CompetitorSearchContext context) {
        Page<Competitor> domains = competitorService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(competitorMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

